package mtc.mtc;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;


public class MainActivity extends ActionBarActivity {

    private View mCmdLayout1;
    private View mCmdLayout2;
    private View mCmdLayout3;
    private View mCmdLayout4;
    private View mCmdLayout5;
    private View mCmdLayout6;
    private View mCmdLayout7;
    private View mCmdLayout8;
    private View mCmdLayout9;
    private static final int DIALOG_CONFIRM_REBOOT = 0;
    private static final int DIALOG_CONFIRM_RECONNECT = 1;
    private static final int DIALOG_CONFIRM_DISCONNECT = 2;

    private int rememberAction = 0;
    private long lastBackPressTime = 0;
    private Toast toast;

    private String model;
    private String host;
    private String username;
    private String password;
    TextView modelText;
    String myIpAdress;
    private int port;
    Boolean saveSession;
    private String restartCmd;
    private String connectCmd;
    private String disconnectCmd;
    private String exitCmd;
    NotificationManager notificationManager;
    private Notification nConnect, nDisconnect;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        overridePendingTransition(R.anim.fadein,R.anim.fadeout);
        setContentView(R.layout.activity_main);

        //Extra
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            modelText = (TextView)findViewById(R.id.textModele);
            model=extras.getString("routerModel");
            username=extras.getString("username");
            password=extras.getString("password");
            myIpAdress=extras.getString("myIp");
            host=extras.getString("host");
            port=extras.getInt("port");
            modelText.setText(model.toUpperCase());
            saveSession=extras.getBoolean("memorise");

            getCommands(model);
        }

        setOnClickAnimation();
        //entryAnimation();
        //setNotifications();


    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void setNotifications() {
        // prepare intent which is triggered if the
        // notification is selected

        Intent cIntent = new Intent(this, MainActivity.class);
        cIntent.putExtra("command", "connect");
        PendingIntent pCIntent = PendingIntent.getActivity(this, 0, cIntent, 0);

        Intent discIntent = new Intent(this, MainActivity.class);
        cIntent.putExtra("command", "disconnect");
        PendingIntent pDiscIntent = PendingIntent.getActivity(this, 0, discIntent, 0);

        // build notification
        nConnect  = new Notification.Builder(this).setContentTitle("MTC").setContentText("Tapez pour retourner à MTC")
                .setSmallIcon(R.drawable.ic_launcher).setContentIntent(pCIntent)
                .setAutoCancel(true).addAction(0, "Reboot", pCIntent).addAction(0, "Connecter", pCIntent)
                .build();

        nDisconnect  = new Notification.Builder(this).setContentTitle("MTC").setContentText("Tapez pour retourner à MTC")
                .setSmallIcon(R.drawable.ic_launcher).setContentIntent(pDiscIntent).setAutoCancel(true)
                .addAction(0, "Reboot", pDiscIntent).addAction(0, "Déconnecter", pDiscIntent)
                .build();

        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        if (isConnected()){
            notificationManager.notify(0, nDisconnect);
        }else {
            notificationManager.notify(0, nConnect);
        }

    }

    private boolean isConnected() {
        //TODO : check ADSL
        return true;
    }


    private void setOnClickAnimation() {
        mCmdLayout1 = findViewById(R.id.container1);
        mCmdLayout1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                animateSimpleButton(view);
                if(rememberAction != 1)
                    showDialog(DIALOG_CONFIRM_REBOOT);
                else {
                    Toast.makeText(getApplicationContext(), "Envoi de la requête de reboot ...", Toast.LENGTH_SHORT).show();
                    doCommand(0);
                }
            }
        });
        mCmdLayout2 = findViewById(R.id.container2);
        mCmdLayout2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                animateSimpleButton(view);
                if(rememberAction != 1)
                    showDialog(DIALOG_CONFIRM_RECONNECT);
                else {
                    Toast.makeText(getApplicationContext(), "Envoi de la requête de reconnexion ADSL ...", Toast.LENGTH_SHORT).show();
                    doCommand(0);
                }
            }
        });
        mCmdLayout3 = findViewById(R.id.container3);
        mCmdLayout3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                animateSimpleButton(view);
                if(rememberAction != 1)
                    showDialog(DIALOG_CONFIRM_DISCONNECT);
                else {
                    Toast.makeText(getApplicationContext(), "Envoi de la requête de déconnexion ADSL ...", Toast.LENGTH_SHORT).show();
                    doCommand(0);
                }
            }
        });
        mCmdLayout4 = findViewById(R.id.container4);
        mCmdLayout4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                animateSimpleButton(view);
            }
        });
        mCmdLayout5 = findViewById(R.id.container5);
        mCmdLayout5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                animateSimpleButton(view);
            }
        });
        mCmdLayout6 = findViewById(R.id.container6);
        mCmdLayout6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                animateSimpleButton(view);
            }
        });
        mCmdLayout7 = findViewById(R.id.container7);
        mCmdLayout7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                animateSimpleButton(view);
            }
        });
        mCmdLayout8 = findViewById(R.id.container8);
        mCmdLayout8.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                animateSimpleButton(view);
            }
        });
        mCmdLayout9 = findViewById(R.id.container9);
        mCmdLayout9.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                animateSimpleButton(view);
            }
        });
    }
    private void entryAnimation() {
        mCmdLayout1.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fadein));
        mCmdLayout2.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fadein));
        mCmdLayout3.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fadein));
        mCmdLayout4.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fadein));
        mCmdLayout5.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fadein));
        mCmdLayout6.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fadein));
        mCmdLayout7.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fadein));
        mCmdLayout8.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fadein));
        mCmdLayout9.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fadein));
    }

    private void animateSimpleButton(View v) {
        v.startAnimation(AnimationUtils.loadAnimation(this, R.anim.zoom_in_out));
        /*ObjectAnimator anim = (ObjectAnimator) AnimatorInflater.loadAnimator(this, R.animator.button_click);
        anim.setTarget(v);
        anim.setDuration(300);
        anim.start();*/
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    @Override
    protected Dialog onCreateDialog(int id) {
        Context context=MainActivity.this;

        final Dialog dialog;
        dialog=new Dialog(context);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.activity_confirm_dialog);
        TextView text=(TextView)dialog.findViewById(R.id.text);
        Button yes;

        //Remember
        final CheckBox remember=(CheckBox)dialog.findViewById(R.id.ChckRememberMe);

        //Submit
        switch (id) {
            case DIALOG_CONFIRM_REBOOT:
                text.setText("Voulez-vous vraiement rebooter le routeur ?");
                yes=(Button)dialog.findViewById(R.id.yes);
                yes.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        if (remember.isChecked()){
                            rememberAction=1;
                        }
                        toast.makeText(getApplicationContext(), "Envoi de la requête de reboot ...", Toast.LENGTH_SHORT).show();
                        doCommand(0);
                    }
                });
                break;
            case DIALOG_CONFIRM_RECONNECT:
                text.setText("Voulez-vous vraiement reconnecter le routeur à l'ADSL ?");
                yes=(Button)dialog.findViewById(R.id.yes);
                yes.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        if (remember.isChecked()){
                            rememberAction=1;
                        }
                        toast.makeText(getApplicationContext(), "Envoi de la requête de reconnexion ADSL ...", Toast.LENGTH_SHORT).show();
                        doCommand(1);
                    }
                });
                break;
            case DIALOG_CONFIRM_DISCONNECT:
                text.setText("Voulez-vous vraiement déconnecter le routeur de l'ADSL ?");
                yes=(Button)dialog.findViewById(R.id.yes);
                yes.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        if (remember.isChecked()){
                            rememberAction=1;
                        }
                        toast.makeText(getApplicationContext(), "Envoi de la requête de déconnexion ADSL ...", Toast.LENGTH_SHORT).show();
                        doCommand(2);
                    }
                });
                break;
            default: break;
        }

        //CANCEL
        Button no = (Button)dialog.findViewById(R.id.no);
        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        return dialog;
    }

    void doCommand(int command){

    }

    public void getCommands(String model){
        Resources resources = this.getResources();
        try {
            InputStream rawResource = resources.openRawResource(R.raw.cmd);
            Properties properties = new Properties();
            properties.load(rawResource);

            restartCmd=properties.getProperty(model+".restart");
            connectCmd=properties.getProperty(model+".connectAdsl");
            disconnectCmd=properties.getProperty(model+".disconnectAdsl");
            exitCmd=properties.getProperty(model+".disconnectAdsl");
            //System.out.println("restartCmd: " + restartCmd + " connectCmd: " + connectCmd + " disconnectCmd: " + disconnectCmd);

        } catch (Resources.NotFoundException e) {
            Toast.makeText(this, "Erreur systeme: fichier command introuvable" + e, Toast.LENGTH_SHORT);
        } catch (IOException e) {
            Toast.makeText(this, "Impossible d'ouvrir le fichier command"+e, Toast.LENGTH_SHORT);
        }
    }


    @Override
    public void onBackPressed() {
        if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
            toast = Toast.makeText(this, "Appuyez encore pour quitter cette fenetre", Toast.LENGTH_SHORT);
            toast.show();
            this.lastBackPressTime = System.currentTimeMillis();
        } else {
            if (toast != null) {
                toast.cancel();
            }
            super.onBackPressed();
        }
    }
}
